﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using SQLiteClient;
using CSKLiteWindowsPhone.Common;
using CSKLiteWindowsPhone.WebsiteData;
using Coding4Fun.Phone.Controls;
using System.IO.IsolatedStorage;
using System.Threading;

namespace CSKLiteWindowsPhone
{
    public partial class TestCases : PhoneApplicationPage
    {
        SQLiteConnection _db = null;
        private WebsiteDataSoapClient _websiteDataClient;
        private string _token = string.Empty;
        private string _userName = string.Empty;

        private Timer refreshTimer;
        public TestCases()
        {
            InitializeComponent();
            this._db = Utility.GetConnection();
            this._token = IsolatedStorageSettings.ApplicationSettings[Constants.LoginTockenKey] as string;
            this._userName = IsolatedStorageSettings.ApplicationSettings[Constants.LoginUserNameKey] as string;

            this.Loaded += new RoutedEventHandler(TestCases_Loaded);
        }

        void  TestCases_Loaded(object sender, RoutedEventArgs e)
        {
            SQLiteCommand cmd = this._db.CreateCommand("select * from TestCase");
            IEnumerable<TestCase> tests = cmd.ExecuteQuery<TestCase>();

            this.reorderListBox.ItemsSource = tests;
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            //progressOverlay.Show();
            this.GetTestCases();
        }

        private void GetTestCases()
        {
            this._websiteDataClient = Utility.GetWebsiteDataSoapClient();
            this._websiteDataClient.GetTestCasesAsync(this._token, this._userName);
            this._websiteDataClient.GetTestCasesCompleted += new EventHandler<GetTestCasesCompletedEventArgs>(_websiteDataClient_GetTestCasesCompleted);
        }

        void _websiteDataClient_GetTestCasesCompleted(object sender, GetTestCasesCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                TestCasesResponse resposne = e.Result;
                this.MaintainTestCases(resposne.TestCases);

                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    ToastPrompt toast = new ToastPrompt();
                    toast.Message = "Refresh succeeded";
                    toast.Show();
                });
            }
            else
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    ToastPrompt toast = new ToastPrompt();
                    Array.ForEach(e.Result.Errors, new Action<Error>((err) => { toast.Message += err.Message; }));
                    toast.Show();
                });
            }

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                this.refreshPanel.IsRefreshing = false;
            });
        }

        private void MaintainTestCases(TestCase[] cases)
        {
            if (this._db != null)
            {

                string sql = @"
CREATE TABLE IF NOT EXISTS TestCase (Id INTEGER PRIMARY KEY,
Type text,
Category text,
InputType text,
Input text,
ProcedureCode int,
Source text,
Description text,
ThreadScope text,
Ace text,
PageIdentificationType text,
PageIdentification text)";
                SQLiteCommand cmd = this._db.CreateCommand(sql);
                int i = cmd.ExecuteNonQuery();

                cmd = this._db.CreateCommand("DELETE FROM TestCase");
                cmd.ExecuteNonQuery();

                foreach (var item in cases)
                {
                    sql = string.Format(@"INSERT INTO TestCase(Id,
Type, 
Category ,
InputType ,
Input ,
ProcedureCode ,
Source ,
Description ,
ThreadScope ,
Ace ,
PageIdentificationType ,
PageIdentification ) VALUES('{11}', '{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}', '{9}', '{10}')",
item.Type,
item.Category,
item.InputType,
item.Input,
item.ProcedureCode,
item.TestSource,
item.Description,
item.ThreatScope,
item.Ace,
string.Empty,
string.Empty,
item.Id);
                    cmd = this._db.CreateCommand(sql);
                    cmd.ExecuteNonQuery();
                }

                cmd = this._db.CreateCommand("select * from TestCase");
                IEnumerable<TestCase> tests = cmd.ExecuteQuery<TestCase>();
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    this.reorderListBox.ItemsSource = tests;
                });
            }
        }

        private void refreshPanel_RefreshRequested(object sender, EventArgs e)
        {
            this.refreshPanel.IsRefreshing = true;
            this.refreshTimer = new Timer(
                delegate
                {
                    // Refresh the fake data!

                    this.GetTestCases();
                },
                null, 3000, -1);
        }
    }
}